/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st.socket.server.netty;

import java.net.InetSocketAddress;
import java.util.Map.Entry;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.bambamboo.st.AbstractIOServer;
import com.bambamboo.st.socket.server.SocketConnectionBean;

/**
 * TCP Server implemented with JBoss Netty
 * <p>
 * Binding socket port and delegate all request to <code>IProecess</code>
 * </p>
 * 
 * @author Nick.Tan
 * @since 1.0.0
 */
public class NettyTCPServer extends AbstractIOServer {

    @Override
    public void startup() throws Exception {
        ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors
                .newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        ChannelPipeline pipeline = bootstrap.getPipeline();
        SocketConnectionBean bean = (SocketConnectionBean) getConnectionBean();
        AbstractChannelHandler channelHandler = new DefaultChannelHandler();
        channelHandler.setConfigurationBean(bean);
        pipeline.addLast("handler", channelHandler);

        for (Entry entry : bean.getOptions().entrySet()) {
            String optname = "child." + entry.getKey();
            bootstrap.setOption(optname, entry.getValue());
        }

        String port = bean.getPort();
        bootstrap.bind(new InetSocketAddress(Integer.parseInt(port)));
    }

    @Override
    public String getType() {
        return "TCP";
    }
}
